import { defineStore } from "pinia"
import { ElNotification } from "element-plus"
import { getAxios } from "/axios"
import Router from "../../router"
const flattenMenuList = []
export const useMenuStore = defineStore("menu", {
	state() {
		return {
			// 路由渲染使用menuList
			menuList: [],
			nowCurrent: -1,
			flattenMenuList: [],
		}
	},
	actions: {
		async getMenu(refresh = false) {
			if (!refresh && this.menuList.length) {
				return this.menuList
			}
			try {
				flattenMenuList.length = 0
				//authority
				this.menuList = buildTree(await getAxios("/system/menu/authority"), {
					title: ["首页"],
					path: ["/"],
					id: [""],
					indexs: [-1],
				})
				forEachMenuList(this.menuList, menu => {
					flattenMenuList.push(menu)
					return false
				})
				this.flattenMenuList = flattenMenuList
				return this.menuList
			} catch (error) {
				ElNotification({ message: error, type: "error" })
				throw new Error(error)
			}
		},
		findInMenuList(path = Router.currentRoute.value.path) {
			return flattenMenuList.find(item => item.path === path)
		},
	},
	getters: {
		childrenMenuList() {
			const menuList = []
			for (let i = 0; i < this.menuList.length; i++) {
				const menu = this.menuList[i]
				if (menu.children) {
					menuList.push(menu.children)
				} else {
					menuList.push([])
				}
			}
			return menuList
		},
		nowChildrenMenuList() {
			if (this.nowCurrent < 0) {
				return this.menuList[0]?.children || []
			}
			return this.menuList[this.nowCurrent].children
		},
	},
})
function buildTree(menuList = [], parent, callback) {
	return menuList.map((menu, index) => {
		const data = {
			id: menu.id,
			title: menu.name,
			path: menu.viewPath,
			icon: menu.icon || "",
			permissions: menu.permissions,
			children: menu.children?.length
				? buildTree(
						menu.children,
						{
							title: parent.title.concat(menu.name),
							path: parent.path.concat(menu.viewPath),
							id: parent.id.concat(menu.id),
							indexs: parent.indexs.concat(index),
						},
						callback
				  )
				: [],
			parent,
		}
		callback && callback(data)
		return data
	})
}
function forEachMenuList(menuList = [], callback, done) {
	for (let i = 0; i < menuList.length; i++) {
		const menu = menuList[i]
		if (callback && callback(menu)) {
			done && done(menu)
			return
		}
		if (menu.children?.length) {
			forEachMenuList(menu.children, callback, done)
		}
	}
}
